package de.metalcon.gwt.client;

import java.util.ArrayList;

import com.google.gwt.user.client.History;

import de.metalcon.gwt.client.interactions.AInteraction;
import de.metalcon.gwt.client.interactions.LoginForm;
import de.metalcon.gwt.client.pages.APage;
import de.metalcon.gwt.client.pages.HomePage;
import de.metalcon.gwt.client.pages.SQLTest;
import de.metalcon.gwt.client.pages.State404;
import de.metalcon.gwt.client.pages.StreamPage;
import de.metalcon.gwt.client.pages.Team;
import de.metalcon.gwt.client.pages.Test;
import de.metalcon.gwt.client.pages.UserPage;
import de.metalcon.gwt.client.pages.WikiPage;

public class HistoryTokenAnalyzer {

	private static final String PARAMETER_DELIMITER = "_";
	private static final String PARAMETER_DELIMITER_REGEX = "_";

	/**
	 * 
	 * @return All params/request variables for the current page
	 */
	public static String[] getPageParams() {
		String token = History.getToken();
		String[] params = token.split(PARAMETER_DELIMITER_REGEX);

		// params[0] is the page name -> ignore it!
		String[] paramList = new String[params.length - 1];
		for (int i = 1; i < params.length; i++) {
			paramList[i - 1] = params[i];
		}
		return paramList;
	}

	public static String GeneratePageToken(String pagePrefix, String[] params) {
		String token = pagePrefix;
		for (String s : params) {
			token += PARAMETER_DELIMITER + s;
		}
		return token;
	}

	public static APage GeneratePageFromHistory() {
		String token = History.getToken();

		if (token.startsWith(Team.getHistoryTokenPrefix())) {
			return new Team();
		}
		if (token.startsWith(WikiPage.getHistoryTokenPrefix())) {
			return new WikiPage(getPageParams());
		}
		if (token.startsWith(StreamPage.getHistoryTokenPrefix())) {
			return new StreamPage(getPageParams());
		}

		if (token.startsWith(HomePage.getHistoryTokenPrefix())) {
			return new HomePage();
		}

		if (token.startsWith(State404.getHistoryTokenPrefix())) {
			return new State404();
		}

		if (token.startsWith(Test.getHistoryTokenPrefix())) {
			return new Test();
		}

		if (token.startsWith(SQLTest.getHistoryTokenPrefix())) {
			return new SQLTest();
		}

		if (token.startsWith(UserPage.getHistoryTokenPrefix())) {
			return new UserPage(getPageParams());
		}

		return null;
	}

	public static ArrayList<AInteraction> GenerateInteractionsFromHistory() {
		ArrayList<AInteraction> modules = new ArrayList<AInteraction>();

		String token = History.getToken();

		if (!token.contains("$")) {
			return modules;
		}

		token = token.substring(token.indexOf('$') + 1);
		String[] interactionTokens = token.split("\\$");

		for (String interaction : interactionTokens) {
			if (interaction.equals(LoginForm.getHistoryTokenPrefix())) {
				modules.add(new LoginForm());
			}
		}

		return modules;
	}
}
